<script lang="ts" setup>

//接一下返回页面0的方法
import {ref, onBeforeUnmount} from "vue";
import type {SaleAttr, SkuData, SpuData, SpuImg} from "../../../api/product/spu/type.ts";
import type {Attr} from "../../../api/product/attr/type.ts";
import {reqAddSku, reqSpuHasSaleAttr, reqSpuImageList} from "../../../api/product/spu";
import {reqAttr} from "../../../api/product/attr";
import { ElMessage } from 'element-plus';

//引入仓库
import useCategoryStore from "../../../store/modules/category";

const categoryStore = useCategoryStore();

const emits = defineEmits(["backPage"]);//获取父组件自定义事件

const imgList = ref<SpuImg[]>([]);//图片列表
const attrList = ref<Attr[]>([]);//属性列表
const saleAttrList = ref<SaleAttr[]>([]);//销售属性列表
const table = ref();//展示图片表格的的表格实例

//定义skuParmas
const skuParams = ref<SkuData>({
  category3Id: '',
  spuId: '',
  tmId: '',
  skuName: '',
  price: '',
  weight: '',
  skuDesc: '',
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
  skuDefaultImg: ''
});

//通过ref获取子组件方法，让父组件在调用的子组件方法时，发请求
const initAddSku = async (spu: SpuData) => {
  //清空数据
  skuParams.value = {
    category3Id: categoryStore.c3Id,
    spuId: spu.id || '',
    tmId: spu.tmId || '',
    skuName: '',
    price: '',
    weight: '',
    skuDesc: '',
    skuAttrValueList: [],
    skuSaleAttrValueList: [],
    skuDefaultImg: ''
  };

  //发请求
  const result1 = await reqSpuImageList(spu.id);
  const result2 = await reqAttr(categoryStore.c1Id, categoryStore.c2Id, categoryStore.c3Id);
  const result3 = await reqSpuHasSaleAttr(spu.id);
  //接受数据
  imgList.value = result1.data;
  attrList.value = result2.data;
  saleAttrList.value = result3.data;
}

defineExpose({initAddSku});//暴露方法

//设置图片
const setImg = (row: SpuImg) => {
  //此乃设置图片选中方式
  imgList.value.forEach(item => {
    if (item === row) {
      table.value.toggleRowSelection(item, true);
    } else {
      table.value.toggleRowSelection(item, false);
    }
  });
  //收集图片才是王道
  if (row.imageUrl != null) {
    skuParams.value.skuDefaultImg = row.imageUrl;
  }
}

//保存sku
const addSku = async () => {
  skuParams.value.skuAttrValueList = attrList.value.reduce((prev, cur) => {
    if (cur.attrAndValue) {
      const [attrId, attrValueId] = (cur.attrAndValue as string).split(":");
      prev.push({attrId, attrValueId});
    }
    return prev;
  }, []);
  skuParams.value.skuSaleAttrValueList = saleAttrList.value.reduce((prev, cur) => {
    if (cur.saleAndValue) {
      const [saleAttrId, saleAttrValueId] = (cur.saleAndValue as string).split(":");
      prev.push({saleAttrId, saleAttrValueId});
    }
    return prev;
  }, []);
  console.log(skuParams.value)
  const result = await reqAddSku(skuParams.value);
  if (result.code === 200) {
    ElMessage({
      type: "success",
      message: "保存成功"
    })
    emits("backPage");
  } else {
    ElMessage({
      type: "error",
      message: "保存失败"
    });
  }
}
</script>

<template>
  <el-form label-width="100px">
    <el-form-item label="sku名称">
      <el-input v-model.trim="skuParams.skuName" placeholder="SKU名称" type="text"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)">
      <el-input v-model.number="skuParams.price" placeholder="价格(元)" type="number"></el-input>
    </el-form-item>
    <el-form-item label="重量(克)">
      <el-input v-model.number="skuParams.weight" placeholder="重量(克)" type="number"></el-input>
    </el-form-item>
    <el-form-item label="sku描述">
      <el-input v-model.lazy="skuParams.skuDesc" placeholder="sku描述" type="textarea"></el-input>
    </el-form-item>
    <el-form-item label="平台属性">
      <el-form inline>
        <el-form-item v-for="(item) in attrList" :key="item.id" :label="item.attrName">
          <el-select v-model="item.attrAndValue" style="width: 150px;">
            <el-option v-for="(item1) in item.attrValues" :key="item1.id" :label="item1.valueName"
                       :value="`${item.id}:${item1.id}`"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-form inline>
        <el-form-item v-for="(item) in saleAttrList" :key="item.id" :label="item.saleAttrName">
          <el-select v-model="item.saleAndValue" style="width: 150px;">
            <el-option v-for="(item1) in item.spuSaleAttrValueList" :key="item1.id"
                       :label="item1.saleAttrValueName" :value="`${item.id}:${item1.id}`"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="图片名称">
      <el-table ref="table" :data="imgList" border>
        <el-table-column align="center" type="selection" width="80px"></el-table-column>
        <el-table-column label="图片">
          <template #default="{row}">
            <img :src="row.imageUrl" alt="" style="width: 100px; vertical-align: middle">
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imageName"></el-table-column>
        <el-table-column label="操作">
          <template #default="{row}">
            <el-button type="warning" @click="setImg(row)">设置默认</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item label="操作">
      <el-button type="primary" @click="addSku">保存</el-button>
      <el-button type="info" @click="emits('backPage', 0)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<style lang="scss" scoped>

</style>